package top.codedance.iotp.tools.serverTool.ui;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.iot.sdk.StandandService;
import top.codedance.iotp.iot.sdk.entity.DeviceEntity;
import top.codedance.iotp.iot.sdk.po.sync.AddDeviceParam;
import top.codedance.iotp.iot.sdk.po.sync.BaseParam;
import top.codedance.iotp.tools.owner.ToolCallOwner;
import top.codedance.iotp.tools.serverTool.ServerToolApplication;
import top.codedance.iotp.tools.terminal.TerminalApplication;
import top.codedance.iotp.tools.terminal.ui.WaitLoading;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @author Lenovo
 */
public class GenDeviceFrame extends javax.swing.JDialog {
    private WaitLoading waitLoading = new WaitLoading(this);
    private MainFrame mf;
    private StandandService standandService;
    private BaseParam baseParam;
    private DefaultTableModel dtm;
    private ToolCallOwner owner = null;
    private int type = -1;

    /**
     * Creates new form GenDeviceFrame
     */
    public GenDeviceFrame(MainFrame mf) {
        super(mf, true);
        this.mf = mf;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setMinimumSize(new Dimension(1062, 643));
        setLocationRelativeTo(this.mf.getShellFrame());
        setTitle("代码飞舞采控系统-生成设备ID");
        this.standandService = new StandandService(ServerToolApplication.serverConf.getServerHost());
        baseParam = new BaseParam();
        baseParam.setUsername(ServerToolApplication.serverConf.getUsername());
        baseParam.setPassword(ServerToolApplication.serverConf.getPassword());
        jb_saveToComponent.setEnabled(false);

        initTable();
    }

    public GenDeviceFrame(MainFrame mf, ToolCallOwner owner, int type) {
        this(mf);
        this.owner = owner;
        this.type = type;
        jb_saveToComponent.setEnabled(true);
    }

    private void initTable() {
        String[] columnNames = {"deviceId"};
        Object[][] tdata = new Object[0][0];
        dtm = new DefaultTableModel(tdata, columnNames);
        device_jt.setModel(dtm);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        genBtn = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        genNumField = new javax.swing.JTextField();
        cleanGenedBtn = new javax.swing.JButton();
        updateRemoteBtn = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        device_jt = new javax.swing.JTable();
        jb_saveToComponent = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setSize(new java.awt.Dimension(400, 300));

        genBtn.setText("生成");
        genBtn.setToolTipText("");
        genBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                genBtnActionPerformed(evt);
            }
        });

        jLabel1.setText("生成数量: ");

        genNumField.setText("1");

        cleanGenedBtn.setText("清空");
        cleanGenedBtn.setToolTipText("");
        cleanGenedBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cleanGenedBtnActionPerformed(evt);
            }
        });

        updateRemoteBtn.setText("更新远程");
        updateRemoteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateRemoteBtnActionPerformed(evt);
            }
        });

        device_jt.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        device_jt.setToolTipText("");
        device_jt.setRowHeight(30);
        jScrollPane2.setViewportView(device_jt);

        jb_saveToComponent.setText("保存到请求组件");
        jb_saveToComponent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_saveToComponentActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jb_saveToComponent)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(genNumField, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(genBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cleanGenedBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(updateRemoteBtn))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 545, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(genBtn)
                    .addComponent(genNumField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cleanGenedBtn)
                    .addComponent(updateRemoteBtn)
                    .addComponent(jLabel1)
                    .addComponent(jb_saveToComponent))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void genBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_genBtnActionPerformed
        String gennum = genNumField.getText();
        int num = Integer.parseInt(gennum);
        if (num <= 0) {
            num = 1;
        }
        for (int i = 0; i < num; i++) {
            dtm.addRow(new String[]{UUID.randomUUID().toString()});
        }
    }//GEN-LAST:event_genBtnActionPerformed

    private void cleanGenedBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cleanGenedBtnActionPerformed
        initTable();
    }//GEN-LAST:event_cleanGenedBtnActionPerformed

    private void updateRemoteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateRemoteBtnActionPerformed
        waitLoading.open();
        TerminalApplication.pool.submit(() -> {
            try {
                AddDeviceParam addDeviceParam = new AddDeviceParam();
                addDeviceParam.setUsername(baseParam.getUsername());
                addDeviceParam.setPassword(baseParam.getPassword());
                ArrayList<DeviceEntity> devices = new ArrayList<>();
                for (int i = 0; i < dtm.getRowCount(); i++) {
                    String v = (String) dtm.getValueAt(i, 0);
                    DeviceEntity de = new DeviceEntity();
                    de.setDeviceId(v);
                    de.setUnitName(v.substring(v.lastIndexOf("-") + 1));
                    devices.add(de);
                }
                addDeviceParam.setDevices(devices);
                JSONObject jsonObject = standandService.addDevices(addDeviceParam);
                Integer status = jsonObject.getInteger("status");
                if (status == 200) {
                    JOptionPane.showMessageDialog(rootPane, "更新成功");
                } else {
                    JOptionPane.showMessageDialog(rootPane, "请求失败：" + jsonObject.getString("message"));
                }
            }catch (Exception e){
                JOptionPane.showMessageDialog(rootPane, "更新失败");
            }finally {
                waitLoading.close();
            }
        });
    }//GEN-LAST:event_updateRemoteBtnActionPerformed

    private void jb_saveToComponentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_saveToComponentActionPerformed
        if(owner != null) {
            owner.setValue((String) dtm.getValueAt(0, 0), type);
            this.setVisible(false);
        }
    }//GEN-LAST:event_jb_saveToComponentActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cleanGenedBtn;
    private javax.swing.JTable device_jt;
    private javax.swing.JButton genBtn;
    private javax.swing.JTextField genNumField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jb_saveToComponent;
    private javax.swing.JButton updateRemoteBtn;
    // End of variables declaration//GEN-END:variables
}
